package com.rongkang.interview.jvm.quote;

import java.util.HashMap;
import java.util.WeakHashMap;

/**
 * @Description:
 * @author: 荣康
 * @date: 2021/12/17
 *  对于普通的HashMap来说，key置空并不会影响，HashMap的键值对，属于强引用，不会被垃圾回收
 *  对于WeakHashMap，在进行GC操作之后，弱引用的就会被回收
 */
public class WeakHashMapDemo {
    public static void main(String[] args) {
        myHashMap();
        System.out.println("====================");
        myWeakHashMap();
    }

    private static void myWeakHashMap() {
        WeakHashMap<Integer, String> weakHashMap = new WeakHashMap<>();
        Integer integer = new Integer(1);
        String a = "HashMap";
        weakHashMap.put(integer, a);
        System.out.println("map = " + weakHashMap);
        integer=null;
        System.out.println("map = " + weakHashMap);
        System.gc();
        System.out.println("map = " + weakHashMap);
    }

    private static void myHashMap() {
        HashMap<Integer, String> map = new HashMap<>();
        Integer integer = new Integer(1);
        String a = "HashMap";
        map.put(integer, a);
        System.out.println("map = " + map);
        integer=null;
        System.out.println("map = " + map);
        System.gc();
        System.out.println("map = " + map);
    }
}
